<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/10/29
 * Time: 16:09
 */

namespace app\common\model;


use think\Model;

class Coupon extends Model
{
    public function operation($data){
        $query = $this -> where('name', $data['name']);
        $action = false;
        if(isset($data['id'])){
            $action = true;

            $query -> where('id', '<>', $data['id']);
        }
        // 判断该优惠券是否已经存在
        $res = $query -> value('id');
        if($res){
            return echoArr(0, '该优惠券已存在');
        }

        $data['use_start_time'] = strtotime($data['use_start_time']);
        $data['use_end_time'] = strtotime($data['use_end_time']);

        if($data['use_start_time'] >= $data['use_end_time']){
            return echoArr(0, '使用日期不能比结束日期大');
        }

        if($data['type'] == 0){
            $data['send_start_time'] = '';
            $data['send_end_time'] = '';
        }else{
            $data['send_start_time'] = strtotime($data['send_start_time']);
            $data['send_end_time'] = strtotime($data['send_end_time']);

            if($data['send_start_time'] >= $data['send_end_time']){
                return echoArr(0, '发放日期不能比结束日期大');
            }
        }

        $result = $this -> validate(true) -> allowField(true) -> isUpdate($action) -> save($data);
        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    public function resFind($id){
        $res = $this -> find($id);

        $res['use_start_time'] = date('Y-m-d', $res['use_start_time']);
        $res['use_end_time'] = date('Y-m-d', $res['use_end_time']);

        if($res['type'] != 0){
            $res['send_start_time'] = date('Y-m-d', $res['send_start_time']);
            $res['send_end_time'] = date('Y-m-d', $res['send_end_time']);
        }

        return $res;
    }

    public function del($data){
        $res = model('CouponList') -> whereIn('cid', $data) -> where('status', 0) -> select();

        $result = false;
        if(!$res){
            $result = $this -> destroy($data);
        }else{
            return echoArr(0, '此优惠券的用户还未使用，不可删除');
        }

        if(false === $result){
            return echoArr(0, '操作失败');
        }else{
            return echoArr(1, '操作成功');
        }
    }

    /**
     * 更改状态
     */
    public function editStatus($data){
        $result = $this -> validate('Coupon.status') -> allowField(true) -> isUpdate(true) -> save($data);

        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }
}